package com.hfi.observer.demo03;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Created by Administrator on 2017/6/29.
 */
interface Observer{
    void update();
}

class StockObserver implements Observer {

    private String name;
    // Observer必须知道Notifier的状态信息, 所以它里面必须有个当前Notifier的对象成员.
    private Notifier notifier;

    public StockObserver(String name, Notifier notifier) {
        this.name = name;
        this.notifier = notifier;
    }

    @Override
    public void update() {
        System.out.println(notifier.getAction() +" " + name + "关闭股票行情，继续工作 ");
    }
}

class NBAObserver implements Observer {
    private String name;
    private Notifier notifier;
    public NBAObserver(String name, Notifier notifier) {
        this.name = name;
        this.notifier = notifier;
    }

    @Override
    public void update() {
        System.out.println(notifier.getAction() +" " + name + "关闭NBA，继续工作 ");
    }
}

interface Notifier{

    void attach(Observer observer);

    void detach(Observer observer);

    void notifier();

    void setAction(String action);

    String getAction();
}

class Secretary implements Notifier {

    //观察者列表 用LinkedHashSet防止出现重复通知的情况
    private Set<Observer> observers = new LinkedHashSet<>();
    //要观察的状态
    private String action;

    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifier() {
        for (Observer o : observers
                ) {
            o.update();
        }
    }

    @Override
    public void setAction(String action) {
        this.action = action;
    }

    @Override
    public String getAction() {
        return action;
    }
}

class Boss implements Notifier {

    //观察者列表
    private Set<Observer> observers = new LinkedHashSet<>();
    //要观察的状态
    private String action;

    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifier() {
        for (Observer o : observers
                ) {
            o.update();
        }
    }

    @Override
    public void setAction(String action) {
        this.action = action;
    }

    @Override
    public String getAction() {
        return action;
    }
}

public class Test {

    public static void main(String[] args) {
        Boss huhansan = new Boss();

        StockObserver tongshi1 = new StockObserver("魏关姹", huhansan);
        NBAObserver tongshi2 = new NBAObserver("易管查", huhansan);

        //注册两位同事
        huhansan.attach(tongshi1);
        huhansan.attach(tongshi2);
        //解除注册一位同事
        huhansan.detach(tongshi1);
        //发现老板回来
        huhansan.setAction("我胡汉三回来了！");
        //通知
        huhansan.notifier();
    }
}
